/**
 * 产品管理js
 */
var productInfo = {
	curPage : 1,
	pageSize : 10,
	dataCache : null,
    parId:null,
	jjsId:'15',
	startEvent : function() {
		// 按回车键登录事件
		document.onkeydown = function(e) {
			var ev = document.all ? window.event : e;
			if (ev.keyCode == 13) {
				productInfo.curPage = 1;
				productInfo.setPageChange(null);
				productInfo.search();
			}
		};

		$('.subType').click(function() {
			alert($(this).attr("id"));
		});
	},
	getSysParam:function () {
        var url = 'mgr/parameterCtrl/getParameter?name=JJS_ID';
		var cb =function (data) {
            if (data.resultCode == 200) {
                productInfo.jjsId = data.result.value01;
            }
        }
        sendApiNoLoad(url, null, cb, 'GET');
    },
	checkShow : function() {
        if (productInfo.parId == null) {
            $("th.time").hide();
            for(var i=0;i<$("[name=productType02_91]").length;i++){
                $($("[name=productType02_91]")[i]).hide();
                $($("[name=productType02_91]")[i]).hide();
                $($("[name=productType02_94]")[i]).hide();
                $($("[name=productType02_106]")[i]).hide();
                $($("[name=productType02_107]")[i]).hide();
                $($("[name=productType02_109]")[i]).hide();
                //$($("[name=productType02_111]")[i]).show();
				$($("[name=productType02_112]")[i]).hide();
				$($("[name=productType02_114]")[i]).hide();
            }
        } else {
            $("th.time").show();
            for(var i=0;i<$("[name=productType02_91]").length;i++) {
                //$($("[name=productType02_91]")[i]).show();
                //$($("[name=productType02_94]")[i]).show();
                //$($("[name=productType02_106]")[i]).show();
                //$($("[name=productType02_107]")[i]).show();
                //$($("[name=productType02_109]")[i]).show();
                $($("[name=productType02_111]")[i]).hide();
				/*$($("[name=productType02_112]")[i]).show();*/
            }
        }
	},

	bindEvent : function() {
		// 查询
		$('#searchData').click(function() {
			productInfo.curPage = 1;
			productInfo.setPageChange(null);
			productInfo.search();
		});
        $('#goBack').unbind();
        $('#goBack').on(
            'click',
            function() {
                //保留选择项
                var publishType = localStorage.getItem("ProductType02_goBack_publishType") ;
                var prodType = localStorage.getItem("ProductType02_goBack_prodType") ;
                var proTerm = localStorage.getItem("ProductType02_goBack_proTerm") ;
                var proStatus = localStorage.getItem("ProductType02_goBack_proStatus") ;
                var name = localStorage.getItem("ProductType02_goBack_name") ;
				var isTest = localStorage.getItem("ProductType02_goBack_isTest") ;
                $('#searchModForm select[name="publishType"]').val(publishType);
                $('#searchModForm select[name="prodType"]').val(prodType);
                $('#searchModForm select[name="proTerm"]').val(proTerm);
                $('#searchModForm select[name="proStatus"]').val(proStatus);
                $('#searchModForm input[name="name"]').val(name);
				$('#searchModForm select[name="isTest"]').val(isTest);
                productInfo.setPageChange(productInfo.curPage);
                productInfo.search(productInfo.curPage);
            });

		$('#addData').on(
				'click',
				function() {
					var path = APP_ADDRESS
							+ 'mgr/product/productType02/productInfoAdd.jsp';
					art.dialog.open(path, {
						title : '添加产品',
						width : 1000,
						height : 600,
						ok : function() {
							var returnStatus = this.iframe.contentWindow
									.submitForm();
							if (returnStatus) {
								productInfo.setPageChange(null);
								productInfo.search();
							}
							return false;
						},
						cancel : true
					});
				});

	},

	// 设置分页
	setPageChange : function(delCurPage) {
		var url = 'mgr/ProductInfoCtrl/getProductInfoList';
		var publishType = $.trim($('#searchModForm input[name="publishType"]')
				.val());
		var proTerm = $.trim($('#searchModForm select[name="proTerm"]').val());
		var prodType = $
				.trim($('#searchModForm select[name="prodType"]').val());
		var name = $.trim($('#searchModForm input[name="name"]').val());
		var proStatus = $.trim($('#searchModForm select[name="proStatus"]').val());
		var isTest = $.trim($('#searchModForm select[name="isTest"]').val());
		var params = {
			'prodTopType' : 2,
			'curPage' : 1,
			'pageSize' : 99999,
			'publishType' : publishType,
			'prodType' : prodType,
			'proTerm' : proTerm,
			'name' : name,
			'isTest':isTest,
			'proStatus': proStatus,
            'parId':productInfo.parId
		};
		var cb = function(data) {
			if (data.resultCode == 200) {
				var totalCount = data.size;
				var pageTotal = (totalCount / productInfo.pageSize > 0) ? Math
						.ceil(totalCount / productInfo.pageSize) : 1;
				pageHelper.init(pageTotal, totalCount, productInfo.search,
						delCurPage); // 翻页事件
			}
		};
		sendApiNoLoad(url, params, cb, 'POST');
	},

	// 查询系统用户
	search : function(pageIdx) {
        //保留选择项

        var publishType = $('#searchModForm select[name="publishType"]').val();
        var prodType = $('#searchModForm select[name="prodType"]').val();
        var proTerm = $('#searchModForm select[name="proTerm"]').val();
        var proStatus = $('#searchModForm select[name="proStatus"]').val();
		var isTest = $('#searchModForm select[name="isTest"]').val();
        var name = $('#searchModForm input[name="name"]').val();

        localStorage.setItem("ProductType02_goBack_publishType", publishType );
        localStorage.setItem("ProductType02_goBack_prodType", prodType );
        localStorage.setItem("ProductType02_goBack_proTerm", proTerm );
        localStorage.setItem("ProductType02_goBack_proStatus", proStatus );
		localStorage.setItem("ProductType02_goBack_isTest", isTest );
		localStorage.setItem("ProductType02_goBack_name", name );

		var url = 'mgr/ProductInfoCtrl/getProductInfoList';
		if (typeof (pageIdx) != "undefined") {
			productInfo.curPage = pageIdx;
		}
		var publishType = $.trim($('#searchModForm input[name="publishType"]')
				.val());
		var prodType = $
				.trim($('#searchModForm select[name="prodType"]').val());
		var proTerm = $.trim($('#searchModForm select[name="proTerm"]').val());
		var proStatus = $.trim($('#searchModForm select[name="proStatus"]').val());
		var name = $.trim($('#searchModForm input[name="name"]').val());
		var params = {
			'prodTopType' : 2,
			'curPage' : productInfo.curPage,
			'pageSize' : productInfo.pageSize,
			'publishType' : publishType,
			'prodType' : prodType,
			'proTerm' : proTerm,
			'name' : name,
			'isTest':isTest,
			'proStatus' : proStatus,
            'parId':productInfo.parId,

		};
		var cb = function(data) {
			$('#tableList tbody').empty();
			var tr = '';
			if (data.resultCode == 200) {
				if (data.result != null && data.result.length > 0) {
					for (var i = 0; i < data.result.length; i++) {
						var singleObj = data.result[i];

						localStorage.setItem(singleObj.id
								+ "_ProductType02_Key", JSON
								.stringify(singleObj));
						var startSaleTime="";
						if(singleObj.startSaleTime != null){
							 startSaleTime=(new Date(singleObj.startSaleTime)).format('yyyy-MM-dd hh:mm:00');
						}
						var endSaleTime="";
						if(singleObj.endSaleTime != null){
							endSaleTime=(new Date(singleObj.endSaleTime)).format('yyyy-MM-dd hh:mm:00');
						}
						var saleOutTime="";
						if(singleObj.saleOutTime != null){
							saleOutTime=(new Date(singleObj.saleOutTime)).format('yyyy-MM-dd hh:mm:00');
						}
						tr += '<tr><td><input type="hidden" name="id" value="'
								+ singleObj.id
								+ '"/>'
								+ '<input type="hidden" name="productName" value="'
								+ singleObj.name
								+ '"/>'
								+ (i + 1)
								+ '</td><td>'
								+ singleObj.name;

						if(productInfo.parId != null && productInfo.parId != ''){
							tr += '</td><td>'
								+  startSaleTime
								+ '</td><td>'
								+  endSaleTime
								+ '</td><td>'
								+  saleOutTime;
						}

						tr += '</td><td>'
								+ singleObj.issuerStr
								+ '</td><td>'
								+jsUtils.getFormatMoney( singleObj.financingAccount)
								+ '</td><td>'
								+ jsUtils.getFormatMoney(singleObj.bespeakAccount)
								+ '</td><td>'
								+ jsUtils.getFormatMoney(singleObj.yraiseAccount)
								+ '</td><td>'
								+ jsUtils.getDictionaryTxtByType('proStatus',
										singleObj.proStatus)
								+ '</td><td>'
								+singleObj.hotSaleStr
								+ '</td><td>'
								+ '<a type="button" name="productType02_94"   class="time btn btn-primary btn-xs bespeak" style="margin-left: 5px; margin-top: 5px; display:none;">'
								+ '<i class="fa fa-reorder" style="margin-right:2px;"></i> 预约 </a>'
								+ '<a type="button" name="productType02_99"   class="btn btn-primary btn-xs lookData" style="margin-left: 5px; margin-top: 5px; display:none;">'
								+ '<i class="fa fa-reorder" style="margin-right:2px;"></i> 查看 </a>'
								+ '<a type="button" name="productType02_96"   class="btn btn-success btn-xs updateData" style="margin-left: 5px; margin-top: 5px; display:none;">'
								+ '<i class="fa fa-edit" style="margin-right:2px;"></i>修改</a>'
								+ '<a type="button" name="productType02_100"  class="btn btn-success btn-xs copyData" style="margin-left: 5px; margin-top: 5px; display:none;">'
								+ '<i class="fa fa-copy" style="margin-right:2px;"></i>一键复制</a>'
								+ '<a type="button" name="productType02_91"   class="time btn btn-success btn-xs updateStatus" style="margin-left: 5px; margin-top: 5px; display:none;">'
								+ '<i class="fa fa-edit" style="margin-right:2px;"></i>更改状态</a>'
                                + '<a type="button" name="productType02_106"  class="time btn btn-success btn-xs transfer" style="margin-left: 5px; margin-top: 5px; display:none;">'
                                + '<i class="fa fa-arrow-right" style="margin-right:1px;"></i>起标划拨</a>';

						if(checkContain(productInfo.jjsId,singleObj.issuerId)){ //金交所产品
                            tr += '<a type="button" name="productType02_107"  class="time btn btn-success btn-xs specialPayBack"  style="margin-left: 5px; margin-top: 5px; display:none;">'
                                + '<i class="fa fa-arrow-left" style="margin-right:1px;"></i>金交所回款</a>';
						}else{
							tr += '<a type="button" name="productType02_107"  class="time btn btn-success btn-xs transferBack" style="margin-left: 5px; margin-top: 5px; display:none;">'
                                + '<i class="fa fa-arrow-left" style="margin-right:1px;"></i>回款划拨</a>';
						}

						tr += '<a type="button" name="productType02_109"  class="time btn btn-success btn-xs setSaleTime" style="margin-left: 5px; margin-top: 5px; display:none;">'
							    + '<i class="fa fa-th" style="margin-right:1px;"></i>自动上下架</a>'
                                + '<a type="button" name="productType02_111"  class="btn btn-success btn-xs showSubProd"  style="margin-left: 5px; margin-top: 5px; display:none;">'
                                + '<i class="fa fa-search" style="margin-right:1px;"></i>查看子标</a>'
                                + '<a type="button" name="productType02_112"  class="btn btn-success btn-xs updFlag"  style="margin-left: 5px; margin-top: 5px; display:none;">'
                                + '<i class="fa fa-edit" style="margin-right:1px;"></i>标签管理</a>'
                                + '<a type="button" name="productType02_114"  class="btn btn-success btn-xs coupon"  style="margin-left: 5px; margin-top: 5px; display:none;">'
                                + '<i class="fa fa-edit" style="margin-right:1px;"></i>适用卡券</a>'
								+ '</td></tr>';
					}
				} else {
					tr = '<tr><td colspan="7" style="text-align:center;color: #ff0000;">暂无数据</td></tr>';
				}
			} else {
				tr = '<tr><td colspan="7" style="text-align:center;color:red;">暂无数据</td></tr>';
			}
			$('#tableList tbody').html(tr);
			productInfo.bindEventOtherBtn();
			jsUtils.controlFunctionBtn();
            productInfo.checkShow();
		};
		sendApiNoLoad(url, params, cb, 'POST');
	},

	bindEventOtherBtn : function() {
		$('.bespeak').unbind();
		$('.bespeak').on(
				'click',
				function() {
					var thisObj = $(this);
					var id = thisObj.parent().parent().find('input[name="id"]')
							.eq(0).val();
					var productName = thisObj.parent().parent().find(
							'input[name="productName"]').eq(0).val();

					art.dialog.data('productId', id);

					art.dialog.data('productName', productName);

					var path = APP_ADDRESS
							+ 'mgr/trade/bespeak/bespeakAdd.jsp';
					art.dialog.open(path, {
						title : '产品预约',
						width : 500,
						height : 200,
						ok : function() {
							var returnStatus = this.iframe.contentWindow
									.submitForm();
							if (returnStatus) {
								productInfo.setPageChange(productInfo.curPage);
								productInfo.search(productInfo.curPage);
							}
							return false;
						},
						cancel : true
					});
				});
		$('.deleteData').unbind();
		$('.deleteData').on(
				'click',
				function() {
					var thisObj = $(this);
					art.dialog.confirm('你确认删除？', function() {
						var id = thisObj.parent().parent().find(
								'input[name="id"]').eq(0).val();
						var url = 'mgr/ProductInfoCtrl/deleteProductInfo';
						var params = {
							'id' : id
						};
						var cb = function(data) {
							alert('删除成功！');
							productInfo.setPageChange(productInfo.curPage);
							productInfo.search(productInfo.curPage);
						}
						sendApiNoLoad(url, params, cb, 'POST');
					}, function() {
					});
				});

		$('.updateData').unbind();
		$('.updateData')
				.on(
						'click',
						function() {
							var thisObj = $(this);
							var id = thisObj.parent().parent().find(
									'input[name="id"]').eq(0).val();
							art.dialog.data('updId', id);
							var path = APP_ADDRESS
									+ 'mgr/product/productType02/productInfoUpdate.jsp';
							art.dialog
									.open(
											path,
											{
												title : '修改产品',
												width : 1000,
												height : 500,
												ok : function() {
													var returnStatus = this.iframe.contentWindow
															.submitForm();
													if (returnStatus) {
														art.dialog.close();
														productInfo
																.setPageChange(productInfo.curPage);
														productInfo
																.search(productInfo.curPage);
													}
													return returnStatus;
												},
												cancel : true
											});
						});
		$('.updFlag').unbind();
		$('.updFlag')
			.on(
				'click',
				function() {
					var thisObj = $(this);
					var id = thisObj.parent().parent().find(
						'input[name="id"]').eq(0).val();
					art.dialog.data('updId', id);
					var path = APP_ADDRESS
						+ 'mgr/product/productType02/productInfoFlag.jsp';
					art.dialog
						.open(
							path,
							{
								title : '标签管理',
								width : 800,
								height : 450,
								ok : function() {
									var returnStatus = this.iframe.contentWindow
										.submitForm();
									if (returnStatus) {
										art.dialog.close();
										productInfo
											.setPageChange(productInfo.curPage);
										productInfo
											.search(productInfo.curPage);
									}
									return returnStatus;
								},
								cancel : true

							});
				});
		$('.copyData').unbind();
		$('.copyData').on(
				'click',
				function() {
					var thisObj = $(this);
					art.dialog.confirm('你确认复制？', function() {
						var id = thisObj.parent().parent().find(
								'input[name="id"]').eq(0).val();
						var url = 'mgr/ProductInfoCtrl/copy';
						var params = {
							'id' : id
						};
						var cb = function(data) {
							alert(data.msg);
							productInfo.setPageChange(productInfo.curPage);
							productInfo.search(productInfo.curPage);
						}
						sendApiNoLoad(url, params, cb, 'POST');
					}, function() {
					});
				});
        $('.showSubProd').unbind();
        $('.showSubProd').on(
            'click',
            function() {
                var thisObj = $(this);
                var id = thisObj.parent().parent().find(
                    'input[name="id"]').eq(0).val();
                productInfo.parId=id;
                productInfo.setPageChange(1);
                productInfo.search(1);
            });
		$('.updateStatus').unbind();
		$('.updateStatus')
				.on(
						'click',
						function() {
							var thisObj = $(this);
							var id = thisObj.parent().parent().find(
									'input[name="id"]').eq(0).val();
							art.dialog.data('updId', id);
							var path = APP_ADDRESS
									+ 'mgr/product/productType02/productInfoUpdateStatus.jsp';
							art.dialog
									.open(
											path,
											{
												title : '更改产品状态',
												width : 400,
												height : 300,
												ok : function() {
													var returnStatus = this.iframe.contentWindow
															.submitForm();
													if (returnStatus) {
														productInfo
																.setPageChange(productInfo.curPage);
														productInfo
																.search(productInfo.curPage);
													}
													return false;
												},
												cancel : true
											});
						});
        $('.setSaleTime').unbind();
        $('.setSaleTime')
            .on(
                'click',
                function() {
                    var thisObj = $(this);
                    var id = thisObj.parent().parent().find(
                        'input[name="id"]').eq(0).val();
                    art.dialog.data('updId', id);
                    var path = APP_ADDRESS
                        + 'mgr/product/productType02/productInfoSetSaleTime.jsp';
                    var returnStatus = false;
					art.dialog
                        .open(
                            path,
                            {
                                title : '产品上下架',
                                width : 400,
                                height : 200,
                                ok : function() {
                                    var returnStatus = this.iframe.contentWindow
                                        .submitForm();
                                    if(returnStatus){
                                        art.dialog.close();
                                        productInfo.setPageChange(productInfo.curPage);
                                        productInfo.search(productInfo.curPage);
                                    }
                                    return returnStatus;
                                },
                                cancel : true
                            });
                });
		$('.transfer').unbind();
		$('.transfer').on('click',
			function() {
				var thisObj = $(this);
				var id = thisObj.parent().parent().find(
						'input[name="id"]').eq(0).val();
				art.dialog.data('transferProId', id);
				var path = APP_ADDRESS
						+ 'mgr/product/productType02/productInfoTransfer.jsp';
				art.dialog.open(
					path,
					{
						title : '产品起标划拨',
						width : 500,
						height : 400,
						ok : function() {
							var returnStatus = this.iframe.contentWindow
									.submitForm();
							if (returnStatus) {
								productInfo
										.setPageChange(productInfo.curPage);
								productInfo
										.search(productInfo.curPage);
							}
							return false;
						},
						cancel : true
					});
			});
		$('.specialPayBack').unbind();
		$('.specialPayBack').on("click",function () {
            var thisObj = $(this);
            var id = thisObj.parent().parent().find(
                'input[name="id"]').eq(0).val();
            var ret = eval('(' + localStorage.getItem(id+"_ProductType02_Key") + ')');
            if(ret.startDiv == 0){
                layer.msg("未起标的产品不能进行回款");
                return;
			}
			var r = confirm("修改前你确认金交所已回款了吗?");
			if(r){
                var url = "mgr/ProductInfoCtrl/specialPayback";
                var params ={
                	"id":id,
					"userId":userId
				}
				var cb = function (data) {
					if(data.resultCode == 200){
                        layer.msg("回款成功");
					}else{
						layer.msg(data.msg);
					}
                }
                sendApiNoLoad(url,params,cb,'POST');
			}
        });
		//$('.transferBack').unbind();
		//$('.transferBack').on('click',
		//		function() {
		//		var thisObj = $(this);
		//		art.dialog.confirm('你确认回款？', function() {
		//			var id = thisObj.parent().parent().find(
		//					'input[name="id"]').eq(0).val();
		//			var url =$("#basePath").val()+'mgr/ProductInfoCtrl/httPayback?productId='+id+"&userId="+userId;
		//			var params =null;
		//			var cb = function(data) {
		//				alert(data.msg);
		//				productInfo.setPageChange(productInfo.curPage);
		//				productInfo.search(productInfo.curPage);
		//			}
		//			getAjax(url, cb, 'GET');
		//			//sendApiNoLoadSync(url, params, cb, 'GET');
		//			//sendApiNoLoad(url, params, cb, 'GET');
		//		}, function() {
		//		});
		//	});

		$('.transferBack').unbind();
		$('.transferBack').on(
				'click',
				function() {
					var thisObj = $(this);
					var id = thisObj.parent().parent().find('input[name="id"]')
							.eq(0).val();
					art.dialog.data('proId', id);
					var path = APP_ADDRESS
							+ 'mgr/product/productType02/productInfoPayBack.jsp';
					art.dialog.open(path, {
						title : '回款划拨',
						width : 700,
						height : 400,
						cancel : true
					});
				});
		$('.lookData').unbind();
		$('.lookData').on(
				'click',
				function() {
					var thisObj = $(this);
					var id = thisObj.parent().parent().find('input[name="id"]')
							.eq(0).val();
					art.dialog.data('lokId', id);
					var path = APP_ADDRESS
							+ 'mgr/product/productType02/productInfoLook.jsp';
					art.dialog.open(path, {
						title : '查看产品',
						width : 900,
						height : 500,
						cancel : true
					});
				});

        $('.coupon').unbind();
        $('.coupon').on(
            'click',
            function() {
                var thisObj = $(this);
                var id = thisObj.parent().parent().find('input[name="id"]')
                    .eq(0).val();
                var productName = thisObj.parent().parent().find(
                    'input[name="productName"]').eq(0).val();

                //如果该产品不可使用优惠券，直接不给打开
                var itermKey =id+"_ProductType02_Key";
                var item = eval('(' + localStorage.getItem(itermKey) + ')');
                if(item["useCard"]== "0"){
                    alert("该产品不可使用优惠券哦！\n可先去产品详情页设置'是否可用优惠券'选择‘是’!");
                    return;
                }


                art.dialog.data('productId', id);
                art.dialog.data('productName', productName);

                var path = APP_ADDRESS
                    + 'mgr/product/productType02/productCoupon.jsp';
                art.dialog.open(path, {
                    title : '适用卡券',
                    width : 900,
                    height : 500,
                    cancel : true
                });
            });
	},

	init : function() {
        productInfo.getSysParam();
		productInfo.checkShow(); productInfo.parProdId=null;
        productInfo.setPageChange(null);
        productInfo.search();
        productInfo.startEvent();
        productInfo.bindEvent();
        jsUtils.controlFunctionBtn();
	}
};

$(function() {
    productInfo.init();
});

//提供给外部刷新调用
function refashData() {
	productInfo.setPageChange(null);
	productInfo.search();
};

function getAjax(url, callback, type,scope) {
	jQuery.ajax({
		type : type,
		contentType : 'application/json',
		url : url,
		timeout : 30000, // 30秒超时
		success : function(result, textStatus) {
			callback.call(scope, result);
		},
		error : function(result) {
			alert(result.status+'请求错误，请稍后再试！');
		}
	});
};

/**
 * 检查value有没有包含key值
 * @param value
 * @param key
 */
function checkContain (value,key) {
	var array = value.split(",");
	var result = false;
	array.forEach(function (val) {
		if(val == key){
			result = true;
		}
    })

	return result;
}

